﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WidgetCache : MonoBehaviour {

	// Use this for initialization
	void Start () {
		
	}

    
    Dictionary<System.Type, Dictionary<string, UnityEngine.GameObject>> m_Dict = new Dictionary<System.Type, Dictionary<string, UnityEngine.GameObject>>();

    public  Dictionary<string, UnityEngine.GameObject> GetDict<T>()
    {
        Dictionary<string, UnityEngine.GameObject> cachesDict;
        m_Dict.TryGetValue(typeof(T), out cachesDict);
        if(cachesDict == null)
        {
            cachesDict = new Dictionary<string, UnityEngine.GameObject>();
            m_Dict[typeof(T)] = cachesDict;
        }
        return cachesDict;
    }

    public UnityEngine.GameObject GetCache<T>(UnityEngine.GameObject pref, string key, out bool newObj)
        where T : MonoBehaviour
    {
        return GetCache<T>(()=>Instantiate(pref),key, out newObj);
    }
    
    public GameObject GetCache<T>(Func<UnityEngine.GameObject> getNewObj, string key, out bool newObj) where T : MonoBehaviour
    {
        newObj = false;

        Dictionary<string, UnityEngine.GameObject> cachesDict = GetDict<T>();

        if (!cachesDict.ContainsKey(key)
           || cachesDict[key] == null)
        {
            var item = getNewObj();
            item.gameObject.SetActive(true);
            cachesDict[key] = item;
            newObj = true;
        }

        return cachesDict[key];
    }

}
